import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { Order, PaginatedResponse } from '../../types';

interface OrderState {
  orders: Order[];
  currentOrder: Order | null;
  total: number;
  loading: boolean;
  error: string | null;
  searchKeyword: string;
  filters: {
    status?: string;
    shopId?: string;
    userId?: string;
  };
  pagination: {
    page: number;
    limit: number;
  };
}

const initialState: OrderState = {
  orders: [],
  currentOrder: null,
  total: 0,
  loading: false,
  error: null,
  searchKeyword: '',
  filters: {},
  pagination: {
    page: 1,
    limit: 20,
  },
};

export const fetchOrders = createAsyncThunk(
  'order/fetchOrders',
  async (params: any, { rejectWithValue }) => {
    try {
      const { OrderService } = await import('../../services/orderService');
      const response = await OrderService.getOrders(params);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.message || '获取订单列表失败');
    }
  }
);

const orderSlice = createSlice({
  name: 'order',
  initialState,
  reducers: {
    setSearchKeyword: (state, action) => {
      state.searchKeyword = action.payload;
    },
    setFilters: (state, action) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    setPagination: (state, action) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchOrders.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchOrders.fulfilled, (state, action) => {
        state.loading = false;
        state.orders = action.payload.data;
        state.total = action.payload.total;
      })
      .addCase(fetchOrders.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { setSearchKeyword, setFilters, setPagination, clearError } = orderSlice.actions;

// 导出选择器
export const selectOrders = (state: any) => state.order.orders;
export const selectOrdersLoading = (state: any) => state.order.loading;
export const selectOrdersTotal = (state: any) => state.order.total;
export const selectOrdersError = (state: any) => state.order.error;
export const selectCurrentOrder = (state: any) => state.order.currentOrder;
export const selectOrdersFilters = (state: any) => state.order.filters;
export const selectOrdersPagination = (state: any) => state.order.pagination;
export const selectOrdersSearchKeyword = (state: any) => state.order.searchKeyword;

export default orderSlice.reducer;
